package br.com.felix.easyclearcase.tasks;

import br.com.felix.commandline.MemoryLog;
import br.com.felix.commandline.SysCommandExecutor;
import br.com.felix.util.ILogDevice;


/**
 * Task for running commands in the runtime environment.
 * @see Task
 * */
public class SystemCommandTask extends Task{

	/**
	 * task cancelled flag
	 * */
	private boolean cancelled = false;
	
	/**
	 * Command to be run on the underlying operational system
	 * */
	private String command;
	
	/**
	 * where the command output will be logged.
	 * */
	private ILogDevice outputLog = new MemoryLog();
	
	/**
	 * where the errors will be logged.
	 * */
	private ILogDevice errorLogger = new MemoryLog();
	
	
	/**
	 * Instantiates a SystemCommandTask with the specified command to be run.
	 * */
	public SystemCommandTask(String cmd){
		this.command = cmd;
	}
	
	
	/**
	 * Triggers the cancel flag.
	 * */
	@Override
	public void cancel() {
		cancelled = true;
	}

	/**
	 * SystemCommandTask priority is HIGH.
	 * */
	@Override
	public TaskPriority getTaskPriority() {
		return TaskPriority.HIGH;
	}

	
	/**
	 * Executes the system command and logs the output.
	 * */
	@Override
	public void run() {
		changeStatus(TaskStatus.IN_PROGRESS);
		SysCommandExecutor cmdexec = new SysCommandExecutor();
		cmdexec.setErrorLogDevice(errorLogger);
		cmdexec.setOutputLogDevice(outputLog);
		try {
			if(!cancelled){
				outputLog.log("Executing system command '"+command+"'.");
				cmdexec.runCommand(command);
				changeStatus(TaskStatus.COMPLETE_SUCCESS);
			}
			else{
				changeStatus(TaskStatus.CANCELLED);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			changeStatus(TaskStatus.COMPLETE_FAIL);
		}
	}

	
	public ILogDevice getErrorLogger() {
		return errorLogger;
	}

	
	public void setErrorLogger(ILogDevice errorLogger) {
		this.errorLogger = errorLogger;
	}

	
	public ILogDevice getOutputLog() {
		return outputLog;
	}

	
	public void setOutputLog(ILogDevice outputLog) {
		this.outputLog = outputLog;
	}
	
	
}
